import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Input, Picker } from '@tarojs/components';
import ImageLoader from '../../components/ImageLoader';

import PageHeader from '../../components/pageHeader';
import { useAppContext } from '../../contexts/AppContext'
import type { CoachItem, CoachPriceItem } from '../../types/coach';
import type { CityBaseItem, RegionNode } from '../../types/cityBase';
import ProcessStatus from '../../components/processStep/processStatus';
import ProvinceCitySelector from '../../components/ProvinceCitySelector';
import { NextButton, PassButton } from '../../components/processStep/processButton';

import { getIdCardValidApi } from '../../api/common';
import { getChinaCityListApi } from '../../api/cityApi';
import { getBasesByCityCodeIdApi } from '../../api/baseApi';
import { createStudentRecordApi, getMyApplyApi } from '../../api/myself';
import { getCoachesByBaseIdApi, getCoachPricesApi } from '../../api/coachApi';

import './index.scss';


/**
 * 用户面签申请页面
 * 用于用户提交驾照面签申请信息
 */
const UserApplyPage: React.FC = () => {
  // 表单状态
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    idCard: '',
    license: 'C2',
    city: '',
    base_id: '',
    coach_id: '',
    price_id: ''
  });

  // 数据状态
  const { carLicenseList } = useAppContext();
  const [prices, setPrices] = useState<CoachPriceItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [coaches, setCoaches] = useState<CoachItem[]>([]);
  const [createTime, setCreateTime] = useState<string>('');
  const [cityBase, setCityBase] = useState<CityBaseItem[]>([]);
  const [chinaCity, setChinaCity] = useState<RegionNode[]>([]);
  const [loadingOptions, setLoadingOptions] = useState<boolean>(true);
  const [formIsDisabled, setFormIsDisabled] = useState<boolean>(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [selectedRegionPath, setSelectedRegionPath] = useState<string[]>([]);
  
  const firstLoadRef = useRef(false);

  /**
   * 获取表单选项数据
   * 包括基地、教练、车型和班型列表
   */
  const fetchOptions = async () => {
    setLoadingOptions(true);

    try {
      // 获取城市信息
      await getChinaCityListApi().then((res) => {
        if (res.code === 200) {
          // 只保留省和市两级数据
          const twoLevelData = res.data.map(province => {
            return {
              id: province.id,
              name: province.name,
              level: 1,
              code: province.id,
              value: province.name,
              children: province.children ? province.children.map(city => {
                return {
                  id: city.id,
                  name: city.name,
                  level: 2,
                  code: city.id,
                  value: city.name,
                  children: []  // 清除区县信息
                };
              }) : []
            };
          });
          setChinaCity(twoLevelData);
        }
      }).catch((error) => {
        console.error('获取城市信息:', error);
        Taro.showToast({
          title: '获取城市信息失败',
          icon: 'none'
        });
      });

      // 检查用户是否已提交申请
      await getMyApplyApi().then((res) => {
        if (res.code === 200 && res.data.has_data) {
          // 已有申请记录，填充表单并禁用
          setCityBase([{
            id: res.data.base_id,
            name: res.data.base_name,
            address: res.data.base_address,
          }]);
          setCoaches([{
            id: res.data.coach_id,
            username: res.data.coach_name,
            avatar: res.data.coach_avatar || '',
            gender: res.data.coach_gender,
          }]);
          setPrices([{
            id: res.data.price_id,
            name: res.data.price_name,
            price: res.data.price,
            license: res.data.price_license,
          }]);
          setCreateTime(res.data.created_at);
          
          // 填充表单数据
          setFormData({
            name: res.data.name || '',
            phone: res.data.phone || '',
            idCard: res.data.card || '',
            license: res.data.license || '',
            city: res.data.region,
            base_id: String(res.data.base_id || ''),
            coach_id: String(res.data.coach_id || ''),
            price_id: String(res.data.price_id || '')
          });
          
          setFormIsDisabled(true);
      
      // 如果有已保存的城市信息，初始化selectedRegionPath
      if (res.data.city) {
        const cityId = String(res.data.city);
        const province = chinaCity.find(p => p.children?.some(c => c.id.toString() === cityId));
        if (province) {
          setSelectedRegionPath([String(province.id), cityId]);
        } else {
          // 如果找不到对应的省份，可能是只有城市ID
          setSelectedRegionPath([cityId]);
        }
      }
        }
      }).catch((error) => {
        console.error('获取我的申请失败:', error);
      });
    } catch (error) {
      console.error('获取数据失败:', error);
      Taro.showToast({
        title: '获取数据失败，请稍后重试',
        icon: 'none'
      });
    } finally {
      setLoadingOptions(false);
    }
  };

  /**
   * 身份证号验证规则
   */
  const idCardValidator = async (value: string): Promise<boolean> => {
    try {
      const res = await getIdCardValidApi(value);
      return res.code === 200 && res.data;
    } catch (error) {
      console.error('身份证验证失败:', error);
      return false;
    }
  };

  /**
   * 手机号验证规则
   */
  const phoneValidator = (value: string): boolean => {
    const reg = /^1[0-9]\d{9}$/;
    return !value || reg.test(value);
  };

  /**
   * 验证表单
   */
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};
    
    if (!formData.name.trim()) {
      newErrors.name = '请输入真实姓名';
    }
    
    if (!formData.phone.trim()) {
      newErrors.phone = '请输入手机号';
    } else if (!phoneValidator(formData.phone)) {
      newErrors.phone = '请输入有效的手机号码';
    }
    
    if (!formData.idCard.trim()) {
      newErrors.idCard = '请输入身份证号码';
    } else if (!idCardValidator(formData.idCard)) {
      newErrors.idCard = '请输入有效的身份证号码';
    }
    
    if (!formData.license) {
      newErrors.license = '请选择车型';
    }
    
    if (!formData.city) {
      newErrors.city = '请选择城市';
    }
    
    if (!formData.base_id) {
      newErrors.base_id = '请选择基地';
    }
    
    if (!formData.coach_id) {
      newErrors.coach_id = '请选择教练';
    }
    
    if (!formData.price_id) {
      newErrors.price_id = '请选择班型';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  /**
   * 处理表单提交
   */
  const handleSubmit = async () => {
    if (!validateForm() || formIsDisabled) {
      return;
    }
    
    try {
      setLoading(true);
      
      // 提交表单数据到后端
      const submitData = {
        ...formData,
        base_id: parseInt(formData.base_id),
        coach_id: parseInt(formData.coach_id),
        price_id: parseInt(formData.price_id)
      };
      
      const res = await createStudentRecordApi(submitData);
      
      if (res.code === 200) {
        Taro.showToast({
          title: '提交成功',
          icon: 'success'
        });
        // 跳转到进度页面
        Taro.navigateTo({
          url: '/pages/user-progress/index?tab=1'
        });
      } else {
        Taro.showToast({
          title: res.message || '提交失败，请稍后重试',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('提交失败:', error);
      Taro.showToast({
        title: '提交失败，请稍后重试',
        icon: 'none'
      });
    } finally {
      setLoading(false);
    }
  };

  /**
   * 处理基地变更
   */
  const changeBase = async (e: any) => {
    const baseId = String(cityBase[e.detail.value].id);
    setFormData(prev => ({
      ...prev,
      base_id: baseId,
      coach_id: '',
      price_id: ''
    }));
    
    setCoaches([]);
    setPrices([]);
    setLoadingOptions(true);
    
    try {
        const response = await getCoachesByBaseIdApi(
          parseInt(baseId), 1, 10000
        );
        if (response.code === 200) {
          // 根据formData.license过滤出对应驾照类型的教练
          const filteredCoaches = response.data.filter(item => {
            // 如果教练没有licenses字段或为空数组，则不过滤
            if (!item.licenses || item.licenses.length === 0) {
              return true;
            }
            // 过滤出拥有formData.license对应驾照类型的教练
            return item.licenses.includes(formData.license);
          }).map(item => ({
            ...item,
            avatar: item.avatar || ''
          }));
          
          setCoaches(filteredCoaches);
        } else {
          console.error('获取教练列表失败:', response.message);
          Taro.showToast({
            title: '获取教练列表失败，请稍后重试',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取教练列表失败:', error);
        Taro.showToast({
          title: '获取教练列表失败，请稍后重试',
          icon: 'none'
        });
      } finally {
        setLoadingOptions(false);
      }
  };

  /**
   * 处理教练变更
   */
  const changeCoach = async (coachId: string) => {
    setFormData(prev => ({
      ...prev,
      coach_id: coachId,
      price_id: ''
    }));
    
    setPrices([]);
    setLoadingOptions(true);
    await getCoachPricesApi(parseInt(coachId)).then(res => {
      if (res.code === 200) {
        setPrices(res.data);
      } else {
        console.error('获取班型列表失败:', res.message);
        Taro.showToast({
          title: '获取班型列表失败，请稍后重试',
          icon: 'none'
        });
      }
    }).catch(err=> {
      console.error('获取班型列表失败:', err);
      Taro.showToast({
        title: '获取班型列表失败，请稍后重试',
        icon: 'none'
      });
    })
  };

  /**
   * 处理城市变更
   */
  const onCityChange = async (cityIds: string[]) => {
    if (cityIds && cityIds.length > 0) {
      const cityId = cityIds[cityIds.length - 1]; // 取最后一级城市ID
      setFormData(prev => ({
        ...prev,
        city: cityId,
        base_id: '',
        coach_id: '',
        price_id: ''
      }));
      
      setCityBase([]);
      setCoaches([]);
      setPrices([]);
      setLoadingOptions(true);
      
      try {
        await getBasesByCityCodeIdApi(parseInt(cityId))
          .then(res => {
            if (res.code == 200) {
              setCityBase(res.data);
            }else {
               Taro.showToast({
                title: '获取驾校列表失败，请稍后重试',
                icon: 'none'
              });
            }
          })
          .catch(error => {
            console.error('获取驾校列表失败:', error);
            Taro.showToast({
              title: '获取驾校列表失败，请稍后重试',
              icon: 'none'
            });
          });
      } finally {
        setLoadingOptions(false);
      }
    }
  };

  /**
   * 处理地区选择
   * @param path 选择的地区ID路径
   * @param node 选择的节点信息
   * @param parentNode 父节点信息
   */
  const handleRegionSelect = (path: string[], node?: RegionNode, parentNode?: RegionNode | null) => {
    // 更新选中的地区路径
    if (node?.level === 1) {
      const children = node.children?.[0];
      setSelectedRegionPath([node.id.toString(), children?.id.toString() || '']);
      node = children;
    }else {
      setSelectedRegionPath(path);
    }
    handleInputChange('city', node?.id?.toString() || '');
    onCityChange([String(node?.id)]);
  };

  const getCityName = (city: string) => {
    const cityId = parseInt(city);
    // 遍历所有省份查找对应的城市
    for (const province of chinaCity) {
      const city = province.children?.find(c => c.id === cityId);
      if (city) {
        return city.name;
      }
    }
    // 如果没有找到城市，尝试查找省份
    return chinaCity.find(p => p.id === cityId)?.name || '请选择城市';
  }
  
  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
    
    // 清除对应字段的错误信息
    if (errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: ''
      }));
    }
  };

  const handleContinueNextStep = async () => {
    Taro.navigateTo({
      url: '/pages/user-drive-hospital/index?stepId=2',
    })
  }

  // 页面加载时获取数据
  useEffect(() => {
    if (!firstLoadRef.current) {
      firstLoadRef.current = true;
      fetchOptions();
    }
  }, []);

  return (
    <View className="page-container">
      <PageHeader title="建立学籍" />
      
      {createTime && (
        <ProcessStatus title="建立学籍" createTime={createTime} />
      )}

      <View className="user-apply-form">
        {/* 姓名 */}
        <View className="user-apply-form-item">
          <View className="user-apply-row">
            <Text className="user-apply-form-item-label">
              <Text className="user-apply-required">*</Text>
              姓名
            </Text>
            <Input
              className={`user-apply-form-input ${errors.name ? 'user-apply-form-error' : ''}`}
              placeholder="真实姓名"
              value={formData.name}
              focus
              onInput={(e) => handleInputChange('name', e.detail.value)}
              disabled={formIsDisabled}
            />
          </View>

          {errors.name && (
            <Text className="user-apply-form-error-message">{errors.name}</Text>
          )}
        </View>

        {/* 手机号码 */}
        <View className="user-apply-form-item">
          <View className="user-apply-row">
            <Text className="user-apply-form-item-label">
              <Text className="user-apply-required">*</Text>手机号码</Text>
            <Input
              className={`user-apply-form-input ${errors.phone ? 'user-apply-form-error' : ''}`}
              placeholder="真实手机号码"
              type="number"
              value={formData.phone}
              onInput={(e) => handleInputChange('phone', e.detail.value)}
              disabled={formIsDisabled}
            />
          </View>
          {errors.phone && (
            <Text className="user-apply-form-error-message">{errors.phone}</Text>
          )}
        </View>

        {/* 身份证 */}
        <View className="user-apply-form-item">
          <View className="user-apply-row">
            <Text className="user-apply-form-item-label">
              <Text className="user-apply-required">*</Text>
              身份证
            </Text>
            <Input
              className={`user-apply-form-input ${errors.idCard ? 'user-apply-form-error' : ''}`}
              placeholder="请输入身份证号码"
              value={formData.idCard}
              onInput={(e) => handleInputChange('idCard', e.detail.value)}
              disabled={formIsDisabled}
            />
          </View>
          {errors.idCard && (
            <Text className="user-apply-form-error-message">{errors.idCard}</Text>
          )}
        </View>

        {/* 车型 */}
        <View className="user-apply-form-item">
          <View className="user-apply-row">
            <Text className="user-apply-form-item-label">
              <Text className="user-apply-required">*</Text>
              车型
            </Text>
            <Picker
              mode="selector"
              className={`user-apply-form-input ${errors.license ? 'user-apply-form-error' : ''}`}
              range={Object.entries(carLicenseList).map(([code, license]) => 
                `【${code}】 ${license.name}`
              )}
              value={Object.keys(carLicenseList).findIndex(code => code === formData.license)}
              onChange={(e) => {
                const code = Object.keys(carLicenseList)[e.detail.value];
                handleInputChange('license', code);
              }}
              disabled={formIsDisabled}
            >
              <View>
                {formData.license ? 
                  `【${formData.license}】 ${carLicenseList[formData.license as keyof typeof carLicenseList]?.name}` : 
                  '请选择车型'}
                <Text className="user-apply-picker-arrow">▼</Text>
              </View>
            </Picker>
          </View>
          {errors.license && (
            <Text className="user-apply-form-error-message">{errors.license}</Text>
          )}
        </View>

        {/* 城市选择 - 省市二级联动下拉选择 */}
        <View className="user-apply-form-item">
          <View className="user-apply-row">
            <Text className="user-apply-form-item-label">
              <Text className="user-apply-required">*</Text>
              城市
            </Text>
            <ProvinceCitySelector 
              level="city"
              chinaRegions={chinaCity}
              onSelect={handleRegionSelect}
              selectedRegionPath={selectedRegionPath}
              class_name="user-apply-form-input"
            >
              <View
              className={`${errors.city ? 'user-apply-form-error' : ''}`}>
                  <Text>{formData.city ? getCityName(formData.city): '请选择城市'}</Text>
                  <Text className="user-apply-picker-arrow">▼</Text>
                </View>
            </ProvinceCitySelector>
          </View>
          {errors.city && (
            <Text className="user-apply-form-error-message">{errors.city}</Text>
          )}
        </View>

        {/* 基地选择 */}
        <View className="user-apply-form-item">
          <View className="user-apply-row">
            <Text className="user-apply-form-item-label">
              <Text className="user-apply-required">*</Text>
              基地
            </Text>
            <Picker
              mode="selector"
              className={`user-apply-form-input ${errors.base_id ? 'user-apply-form-error' : ''}`}
              range={cityBase.length > 0 ? cityBase.map(base => `【${base.name}】 ${base.address}`) : ['当前城市暂无可用基地']}
              value={cityBase.findIndex(base => String(base.id) === formData.base_id)}
              onChange={(e) => { if (cityBase.length > 0) changeBase(e)}}
              disabled={formIsDisabled}
            >
              <View>
                {formData.base_id ? 
                  `${cityBase.find(base => String(base.id) === formData.base_id)?.name || ''}` : 
                  (cityBase.length > 0 ? '请选择基地' : '当前城市暂无可用基地')}
                <Text className="user-apply-picker-arrow">▼</Text>
              </View>
            </Picker>
          </View>
          {errors.base_id && (
            <Text className="user-apply-form-error-message">{errors.base_id}</Text>
          )}
        </View>

        {/* 教练选择 */}
        <View className="user-apply-form-item">
          <View className="user-apply-row">
            <Text className="user-apply-form-item-label"><Text className="user-apply-required">*</Text>教练</Text>
            <Picker
              mode="selector"
              className={`user-apply-form-input ${errors.coach_id ? 'user-apply-form-error' : ''}`}
              range={coaches.length > 0 ? [
                // 将教练信息转换为字符串，便于Picker显示
                ...coaches.map(coach => `${coach.username} (${coach.gender})`),
                // 随机选项
                '随机该基地教练',
                '随机该基地男教练',
                '随机该基地女教练'
              ] : ['当前基地暂无可用教练']}
              value={coaches.findIndex(coach => String(coach.id) === formData.coach_id) !== -1 
                ? coaches.findIndex(coach => String(coach.id) === formData.coach_id) 
                : formData.coach_id === '-1' ? coaches.length 
                : formData.coach_id === '-2' ? coaches.length + 1 
                : formData.coach_id === '-3' ? coaches.length + 2 
                : 0}
              onChange={(e) => {
                if (coaches.length > 0) {
                  let coachId = '-1'; // 默认值
                  if (e.detail.value as number < coaches.length) {
                    // 选择了具体教练
                    coachId = String(coaches[e.detail.value].id);
                  } else if (e.detail.value === coaches.length) {
                    // 随机该基地教练
                    coachId = '-1';
                  } else if (e.detail.value === coaches.length + 1) {
                    // 随机该基地男教练
                    coachId = '-2';
                  } else if (e.detail.value === coaches.length + 2) {
                    // 随机该基地女教练
                    coachId = '-3';
                  }
                  changeCoach(coachId);
                }
              }}
              disabled={formIsDisabled}
            >
              <View>
                {formData.coach_id ? (
                  coaches.find(coach => String(coach.id) === formData.coach_id) ? (
                    <View style={{ display: 'flex', alignItems: 'center' }}>
                      <ImageLoader 
                        src={coaches.find(coach => String(coach.id) === formData.coach_id)?.avatar || ''} 
                        className="user-apply-coach-avatar"
                        mode='aspectFit'
                        style={{ marginRight: '8rpx' }}
                      />
                      <Text className={coaches.find(coach => String(coach.id) === formData.coach_id)?.gender === '男' ? 'user-apply-text-blue' : 'user-apply-text-red'}>
                        {coaches.find(coach => String(coach.id) === formData.coach_id)?.username}
                      </Text>
                    </View>
                  ) : formData.coach_id === '-1' ? '随机该基地教练' : formData.coach_id === '-2' ? '随机该基地男教练' : '随机该基地女教练'
                ) : (coaches.length > 0 ? '请选择教练' : '当前基地暂无可用教练')}
                <Text className="user-apply-picker-arrow">▼</Text>
              </View>
            </Picker>
          </View>
          {errors.coach_id && (
            <Text className="user-apply-form-error-message">{errors.coach_id}</Text>
          )}
        </View>

        {/* 班型选择 */}
        <View className="user-apply-form-item">
          <View className="user-apply-row">
            <Text className="user-apply-form-item-label">
              <Text className="user-apply-required">*</Text>
              班型
            </Text>
            <Picker
              mode="selector"
              className={`user-apply-form-input ${errors.price_id ? 'user-apply-form-error' : ''}`}
              range={prices.map(price => `【￥${price.price}】 ${price.name}`)}
              value={prices.findIndex(price => String(price.id) === String(formData.price_id))}
              disabled={formIsDisabled || prices.length === 0}
              onChange={(e) => {
                const priceId = e.detail.value;
                setFormData(prev => ({
                  ...prev,
                  price_id: prices[priceId].id
                }));
              }}
            >
              <View>
                {formData.price_id ? 
                  `${prices.find(price => String(price.id) === String(formData.price_id))?.name || ''}` : 
                  '选择教练后才能选择班型'}
                <Text className="user-apply-picker-arrow">▼</Text>
              </View>
            </Picker>
          </View>
          {errors.price_id && (
            <Text className="user-apply-form-error-message">{errors.price_id}</Text>
          )}
        </View>

        {/* 提交按钮 */}
        <View style={{marginTop: '20px'}}>
          {formIsDisabled ? (
            <NextButton onClick={handleContinueNextStep}/>
          ) : (
            <PassButton 
              onClick={handleSubmit}
              content="享平台百公里上门接送"
              subText="建 立 学 籍"
              loading={loading}
              disabled={loading || formIsDisabled}
            />
          )}
        </View>

         <View className="user-apply-notice">
              <View className="user-apply-notice-title">
                <MaterialIcons name="info" size={20} color="#e6a23c" className="mr-2" />
                <Text className="user-apply-notice-title-text">特别注意</Text>
              </View>
              <View className="user-apply-notice-content">
                <Text>提交后，由教练进行确认，平台发放接送用车券</Text>
              </View>
            </View>
      </View>
    </View>
  );
};

export default UserApplyPage;